<?php

namespace App\Http\Controllers;

use App\Events\PlayerJoined;
use App\Models\Lotto;
use DB;
use Illuminate\Http\Request;
use App\Models\User;
use View;

class LottoController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only(['show', 'giveAward', 'replay']);
    }

    public function show(Request $request, Lotto $lotto)
    {
        $players = $lotto->players()->orderBy('pivot_created_at', 'desc')->get();

        return view('lotto.show', [
            'lotto'   => $lotto,
            'players' => $players,
        ]);
    }

    public function join(Request $request, Lotto $lotto)
    {
        View::share('lotto', $lotto);

        if (!$lotto->valid) {
            return view('lotto.error', [
                'status' => 'invalid',
            ]);
        }

        $wechatUser = session('wechat.oauth_user')['default'];

        if (!$wechatUser) {
            return view('lotto.error', [
                'status' => 'qr_code',
            ]);
        }

        $userData = $wechatUser->getOriginal();
        $userData = User::convertWechatData($userData);

        $user = User::firstOrCreate([
            'union_id' => $userData['union_id'],
        ], $userData);

        $changes = $lotto->players()->syncWithoutDetaching($user->id);
        if (count($changes['attached']) == 0) {
            $msg = '请勿重复参与';
        } else {
            $pivotId = $changes['attached'][0];
            $lotto->players()->updateExistingPivot($pivotId, ['created_at' => date('Y-m-d H:i:s')]);
            $msg = '已成功参与';
            broadcast(new PlayerJoined($lotto, $user));
        }

        return view('lotto.join_success', compact('user', 'msg'));
    }

    public function giveAward(Request $request, Lotto $lotto)
    {
        $lotto->players()->updateExistingPivot($request->get('userId'), [
            'award' => $request->get('item'),
        ]);

        return response()->json([
            'status' => true,
        ]);
    }

    public function replay(Lotto $lotto)
    {
        DB::table($lotto->players()->getTable())
          ->where('lotto_id', $lotto->id)
          ->update(['award' => null]);

        return response()->json([
            'status' => true,
        ]);
    }

    public function resetCurrent(Request $request, Lotto $lotto)
    {
        DB::table($lotto->players()->getTable())
          ->where('lotto_id', $lotto->id)
          ->whereIn('user_id', $request->get('user_ids'))
          ->update(['award' => null]);

        return response()->json([
            'status' => true,
        ]);
    }
}
